package com.taomus.mytools.test;

import java.lang.reflect.InvocationTargetException;

import org.junit.Test;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.commons.GeneratorAdapter;

import com.taomus.mytools.lang.utils.asm.AsmUtils;
import com.taomus.mytools.lang.utils.asm.CreateClass;
import com.taomus.mytools.lang.utils.asm.ICode;

public class AsmUtilsTestCase {

	@Test
	public void TestField() throws Exception {
		AsmUtils u = new AsmUtils();
		CreateClass czlass = u.createClass("Test");
		czlass.createPrivateField("pstr", String.class);

		czlass.FuncBegin("int Inc()", Opcodes.ACC_PUBLIC).setLocalStore("ainc", int.class, 1).appendCode(new ICode() {
			@Override
			public void code(GeneratorAdapter gadapter) {
				gadapter.iinc(1, 1);
			}
		}).getLocalStore("ainc", int.class).FuncEnd();

		czlass.FuncBegin("String getHello(String,Object)",Opcodes.ACC_PUBLIC)
				.setThis("hello", String.class,"Hello This")
				.getThis("hello")
		 .FuncEnd();

		czlass.FuncPublicBegin("String getHello2(String)")
			.argsToThis(0,"thello",String.class)
			.getThis("thello")
		.FuncEnd();

		czlass.FuncPublicBegin("void testCode(Integer)")
			.invoke("int Inc()")
		.FuncEnd();

		callTest(u);

	}

	private void callTest(AsmUtils u)
			throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		Class<?> cl = u.loadClass2("Test");
		Object obj = cl.newInstance();
		cl.getMethod("setPstr", String.class).invoke(obj, "Hello World");

		int retValue = (int) cl.getMethod("Inc").invoke(obj);
		System.out.println("retValue = " + retValue);
		String retStrValue = (String) cl.getMethod("getHello",String.class,Object.class).invoke(obj,"H","W");
		System.out.println("retValue = " + retStrValue);
		String retStrValue2 = (String) cl.getMethod("getHello2",String.class).invoke(obj,"Hello2 String");
		System.out.println("retValue = " + retStrValue2);
		cl.getMethod("testCode",Integer.class).invoke(obj,1);
		System.out.print(cl.getMethod("getPstr").invoke(obj));
	}

}
